package org.rslai.tcedit.security;

import java.util.Set;
import org.rslai.tcedit.business.UserService;
import org.rslai.tcedit.domain.Role;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;

/**
 * Implementation of UserDetailsService by business service. Need a
 * BusinessService injection.
 * 
 * @author rslai
 */
public class SimpleUserDetailsService implements UserDetailsService {

	private final Log log = LogFactory.getLog(getClass());

	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		if (log.isDebugEnabled()) {
			log.debug("Loading UserDetails of username: " + username);
		}

		org.rslai.tcedit.domain.User user = userService.query(username);

		// 生成此用户所具有的角色信息
		int i = 0;
		Set<Role> roles= user.getRoles();
		GrantedAuthority[] auths = new GrantedAuthority[roles.size()];
		for(Role role : roles) {
			auths[i] = new GrantedAuthorityImpl(role.getName());
			i = i + 1;
		}

		return new CustomUserDetails(
				user.getUsername(),
				user.getPassword(),
				true,
				true,
				true,
				!user.getLocked(),
				auths);
	}

}
